/*
Copyright 2018 Embedded Microprocessor Benchmark Consortium (EEMBC)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Original Author: Shay Gal-on
*/
/*
 * Copyright (c) 2017 - 2022 , NXP
 * All rights reserved.
 */

#include <stdio.h>
#include <stdlib.h>
#include "coremark.h"

/* added for LPC86x platform */
#include "fsl_common.h"
#include "fsl_clock.h"
#include "fsl_gpio.h"
#include "fsl_iocon.h"
#include "fsl_usart.h"
#include "fsl_power.h"
#include "fsl_swm.h"

#include "clock_config.h"
#include <stdbool.h>
#include "clock_config.h"
#include "fsl_debug_console.h"

#include "board.h"
#include "pin_mux.h"

/* User should consider ITERATIONS values */
#define ITERATIONS 600

#define RESULT_OUTPUT 1

#if VALIDATION_RUN
  volatile ee_s32 seed1_volatile=0x3415;
  volatile ee_s32 seed2_volatile=0x3415;
  volatile ee_s32 seed3_volatile=0x66;
#endif
#if PERFORMANCE_RUN
  volatile ee_s32 seed1_volatile=0x0;
  volatile ee_s32 seed2_volatile=0x0;
  volatile ee_s32 seed3_volatile=0x66;
#endif
#if PROFILE_RUN
  volatile ee_s32 seed1_volatile=0x8;
  volatile ee_s32 seed2_volatile=0x8;
  volatile ee_s32 seed3_volatile=0x8;
#endif
  volatile ee_s32 seed4_volatile=ITERATIONS;
  volatile ee_s32 seed5_volatile=0;
  
/* Porting : Timing functions
   How to capture time and convert to seconds must be ported to whatever is supported by the platform.
   e.g. Read value from on board RTC, read value from cpu clock cycles performance counter etc. 
   Sample implementation for standard time.h and windows.h definitions included.
*/
/* Define : TIMER_RES_DIVIDER
   Divider to trade off timer resolution and total time that can be measured.

   Use lower values to increase resolution, but make sure that overflow does not occur.
   If there are issues with the return value overflowing, increase this value.
*/
#define EE_TICKS_PER_SEC 100
volatile uint32_t gTicks; /* Systick counter var. */
#define SysTick_Counter_Disable   ((uint32_t)0xFFFFFFFE)
#define SysTick_Counter_Enable    ((uint32_t)0x00000001)
#define SysTick_Counter_Clear     ((uint32_t)0x00000000)

uint8_t g_testMode = '0';

void BOARD_BootClockLPOSC1MHz(void);

/* Function : start_time
   This function will be called right before starting the timed portion of the benchmark.

   Implementation may be capturing a system timer (as implemented in the example code) 
   or zeroing some system parameters - e.g. setting the cpu clocks cycles to 0.
*/
void start_time(void) {
    GPIO_PinWrite(GPIO, 1, 6, 0);
#if RESULT_OUTPUT
    gTicks = 0;
    /* Enable SystemTick every 1mS */
    SysTick_Config(SystemCoreClock/EE_TICKS_PER_SEC);  
#endif
}

/* Function : stop_time
   This function will be called right after ending the timed portion of the benchmark.

   Implementation may be capturing a system timer (as implemented in the example code) 
   or other system parameters - e.g. reading the current value of cpu cycles counter.
*/
void stop_time(void) {
    GPIO_PinWrite(GPIO, 1, 6, 1);
#if RESULT_OUTPUT
    SysTick->CTRL &= SysTick_Counter_Disable; /* Stop the Timer and get the encoding time */
    SysTick->VAL   = SysTick_Counter_Clear; /* Clear the SysTick Counter */ 
#endif
}
/* Function : get_time
   Return an abstract "ticks" number that signifies time on the system.
   Actual value returned may be cpu cycles, milliseconds or any other value,
   as long as it can be converted to seconds by <time_in_secs>.
   This methodology is taken to accomodate any hardware or simulated platform.
   The sample implementation returns millisecs by default, 
   and the resolution is controlled by <TIMER_RES_DIVIDER>
*/
CORE_TICKS get_time(void) {
    CORE_TICKS elapsed = (CORE_TICKS)gTicks;
    
    return elapsed;
}
/* Function : time_in_secs
   Convert the value returned by get_time to seconds.

   The <secs_ret> type is used to accomodate systems with no support for floating point.
   Default implementation implemented by the EE_TICKS_PER_SEC macro above.
*/
secs_ret time_in_secs(CORE_TICKS ticks) {
    secs_ret retval=((secs_ret)ticks) / (secs_ret)EE_TICKS_PER_SEC;
    return retval;
}

ee_u32 default_num_contexts=1;

/* Function : portable_init
   Target specific initialization code 
   Test for some common mistakes.
*/
volatile uint8_t s_CmdRecv = 0;

void flash_setting_enable(void)
{
    *((volatile unsigned *)(0x40040000)) |= 0x00000010;                         /* Enabled DC Read mode */
}

void flash_setting_disable(void)
{
    *((volatile unsigned *)(0x40040000)) &= 0xFFFFFFEF;                         /* Disabled DC Read mode */
}


void portable_init(core_portable *p, int *argc, char *argv[])
{
  
    CLOCK_Select(BOARD_DEBUG_USART_CLK_ATTACH);
    BOARD_InitBootPins();
    BOARD_BootClockFRO24M();
    BOARD_InitDebugConsole();
     
    ee_printf("\r\nLPC86x CoreMark and Power Consumption Test Program\r\n");
    ee_printf("Please Select the Test Mode\r\n");
    ee_printf("0 - Power Consumption Test\r\n");
    ee_printf("1 - CoreMark Test\r\n");
    USART_ReadBlocking(USART0, (uint8_t *)&g_testMode, 1);
    
    //Power Consumption Test
    if(g_testMode == '0')
    {
      
        ee_printf("\r\nLPC86x Power Consumption Test Program Start\r\n");
        ee_printf("Please Select Core Freqency first by input 1/2/3/4/...\r\n");
        ee_printf("0 - 1MHz  LPOSC \r\n");
        ee_printf("1 - 18MHz FRO \r\n");
        ee_printf("2 - 24MHz FRO \r\n");
        ee_printf("3 - 30MHz FRO \r\n");
        ee_printf("4 - 36MHz FRO \r\n");
        ee_printf("5 - 48MHz FRO \r\n");
        ee_printf("6 - 60MHz FRO \r\n");
        
        USART_ReadBlocking(USART0, (uint8_t *)&s_CmdRecv, 1);        
        
        if(s_CmdRecv == '0')
        {
            ee_printf("SystemCoreClock: 1MHz \r\n");
            BOARD_BootClockLPOSC1MHz();
        }
        
        if(s_CmdRecv == '1')
        {
            ee_printf("SystemCoreClock: 18MHz \r\n");
            BOARD_BootClockFRO18M();
        } 
        if(s_CmdRecv == '2')
        {
            ee_printf("SystemCoreClock: 24MHz \r\n");
            BOARD_BootClockFRO24M();
        } 
        if(s_CmdRecv == '3')
        {
            ee_printf("SystemCoreClock: 30MHz \r\n");
            BOARD_BootClockFRO30M();
        } 
        if(s_CmdRecv == '4')
        {
            ee_printf("SystemCoreClock: 36MHz \r\n");
            BOARD_BootClockFRO36M();
        }
        if(s_CmdRecv == '5')
        {
            ee_printf("SystemCoreClock: 48MHz \r\n");
            BOARD_BootClockFRO48M();
        }
        if(s_CmdRecv == '6')
        {
            ee_printf("SystemCoreClock: 60MHz \r\n");
            BOARD_BootClockFRO60M();
        }      
        
        USART_Deinit(USART0);
        BOARD_InitPins();
        
        CLOCK_DisableClock(kCLOCK_Iocon);     /* Disables clock for IOCON.: disable */
        CLOCK_DisableClock(kCLOCK_Swm);       /* Disables clock for switch matrix.: disable */
        
        /* Disable Peripherals in SYSAHBCLKCTRL */
        SYSCON->SYSAHBCLKCTRL0 &= ~(1<<1);

        while(1)
        {
        }
        
    }
    
    // CoreMark Test
    if(g_testMode == '1')
    {       
        ee_printf("\r\nLPC86x CoreMark Test Program Start\r\n");
        ee_printf("Please Select Core Freqency first by input 1/2/3/4/...\r\n");
        ee_printf("1 - 18MHz FRO   1 access with Flash Buffer \r\n");
        ee_printf("2 - 24MHz FRO   1 access with Flash Buffer \r\n");
        ee_printf("3 - 30MHz FRO   2 access with Flash Buffer \r\n");
        ee_printf("4 - 36MHz FRO   2 access with Flash Buffer \r\n");
        ee_printf("5 - 48MHz FRO   3 access with Flash Buffer \r\n");
        ee_printf("6 - 60MHz FRO   3 access with Flash Buffer \r\n");
        ee_printf("7 - 60MHz FRO   3 access without Flash Buffer \r\n");
    
        USART_ReadBlocking(USART0, (uint8_t *)&s_CmdRecv, 1);

        /* 18MHz FRO with Flash Buffer */
        if(s_CmdRecv == '1')
        {
            FLASH_CTRL->FLASHCFG = 0;
            *((volatile unsigned *)(0x40048240)) = 0x03;       /* Enable Flash Cache */
            BOARD_BootClockFRO18M();
            BOARD_InitDebugConsole();
            seed4_volatile = 300;
        }
    
        /* 24MHz FRO with Flash Buffer */
        if(s_CmdRecv == '2')
        {
            FLASH_CTRL->FLASHCFG = 0;
            *((volatile unsigned *)(0x40048240)) = 0x03;       /* Enable Flash Cache */
            BOARD_BootClockFRO24M();
            BOARD_InitDebugConsole();
            seed4_volatile = 600;
        } 
    
        /* 30MHz FRO with Flash Buffer */
        if(s_CmdRecv == '3')
        {
            FLASH_CTRL->FLASHCFG = 1;
            *((volatile unsigned *)(0x40048240)) = 0x03;       /* Enable Flash Cache */
            BOARD_BootClockFRO30M();
            BOARD_InitDebugConsole();
            seed4_volatile = 800;
        }
    
        /* 36MHz FRO with Flash Buffer */
        if(s_CmdRecv == '4')
        {
            FLASH_CTRL->FLASHCFG = 1;
            *((volatile unsigned *)(0x40048240)) = 0x03;       /* Enable Flash Cache */
            BOARD_BootClockFRO36M();
            BOARD_InitDebugConsole();
            seed4_volatile = 1000;
        }
    
        /* 48MHz FRO with Flash Buffer */
        if(s_CmdRecv == '5')
        {
            FLASH_CTRL->FLASHCFG = 2;
            *((volatile unsigned *)(0x40048240)) = 0x03;       /* Enable Flash Cache */
            BOARD_BootClockFRO48M();
            BOARD_InitDebugConsole();
            seed4_volatile = 1400;
        }

        /* 60MHz FRO with Flash cache, 2wait - 118.296530 */
        if(s_CmdRecv == '6')
        {
            FLASH_CTRL->FLASHCFG = 2;
            *((volatile unsigned *)(0x40048240)) = 0x03;       /* Enable Flash Cache */       
            BOARD_BootClockFRO60M();
            BOARD_InitDebugConsole();
            seed4_volatile = 1500;
        }

        /* 60MHz FRO without Flash Buffer */
        if(s_CmdRecv == '7')
        {
            FLASH_CTRL->FLASHCFG = 2;
            *((volatile unsigned *)(0x40048240)) = 0x00;       /* Disable Flash Cache */
            BOARD_BootClockFRO60M();
            BOARD_InitDebugConsole();
            seed4_volatile = 1500;
        }

        /* Print main clock frequency information */ 
        ee_printf("SystemCoreClock: %d\r\n", SystemCoreClock);
        ee_printf("System Running on FLASH\r\n");

        if (sizeof(ee_ptr_int) != sizeof(ee_u8 *)) {
        ee_printf("ERROR! Please define ee_ptr_int to a type that holds a pointer!\n");
        }
        if (sizeof(ee_u32) != 4) {
            ee_printf("ERROR! Please define ee_u32 to a 32b unsigned type!\n");
        }
        p->portable_id = 1;
    }
    
}


__attribute__((section("criticalFunc"))) void critical_func1(uint32_t n)
{
    PRINTF("Arg = %d .\r\n", n);
}

void BOARD_BootClockLPOSC1MHz(void)
{
    *((volatile unsigned *)(SYSCON_BASE+0x238)) &= ~((1UL<<1) | (1UL<<0));      /* Powered FOR and FROOUT */
    
    *((volatile unsigned *)(SYSCON_BASE+0x050))  = 0x00000000;                  /* Switch Main Clock to FRO */
    *((volatile unsigned *)(SYSCON_BASE+0x054))  = 0x0;
    *((volatile unsigned *)(SYSCON_BASE+0x054))  = 0x1;                         /* Enable Main Clock Source Update */
    
    *((volatile unsigned *)(SYSCON_BASE+0x080))  = 0x00000017;                  /* Set PCONP register value */
    *((volatile unsigned *)(SYSCON_BASE+0x028))  = 0x00028800;                  /* Set FRO ctrl register, 0-36MHz, 1-48MHz, 2-60MHz, divided FRO */
    *((volatile unsigned *)(SYSCON_BASE+0x030))  = 0x0; 
    *((volatile unsigned *)(SYSCON_BASE+0x030))  = 0x1;                         /* Enable FRO Update clock source */
    
    *((volatile unsigned *)(SYSCON_BASE+0x050))  = 0x00000003;                  /* Switch Main Clock to FRO_DIV = FRO/2 */
    
    //*((volatile unsigned *)(SYSCON_BASE+0x024))  = 0x000037AA;                /* Set LPOSC ctrl register */
    *((volatile unsigned *)(SYSCON_BASE+0x238)) &= ~(1UL<<6);                   /* Enable LPOSC: 0-Powered, 1-PowerDown */
    *((volatile unsigned *)(SYSCON_BASE+0x050))  = 0x00000002;                  /* Switch Main Clock to LPOSC */
    *((volatile unsigned *)(SYSCON_BASE+0x054))  = 0x0;
    *((volatile unsigned *)(SYSCON_BASE+0x054))  = 0x1;                         /* Enable Main Clock Source Update */
    
    *((volatile unsigned *)(SYSCON_BASE+0x238)) |= ((1UL<<1) | (1UL<<0));       /* PowerDown/Disable FOR and FROOUT */
    
    SystemCoreClock = 1000000u;
}

/* Function : portable_fini
	Target specific final code 
*/

void portable_fini(core_portable *p)
{
    p->portable_id=0;
    volatile uint8_t s_CmdRecv;


    ee_printf("Test DONE, Press anykey to start again\r\n");
    USART_ReadBlocking(USART0, (uint8_t *)&s_CmdRecv, 1);
    NVIC_SystemReset();     /* Reboot System */

    while(1)
    {
        __WFI();
    }
}

/* Systick ISR. */
void SysTick_Handler(void)
{
    gTicks++;
}

void BOD_DriverIRQHandler(void)
{
    gTicks++;
}
